/**
 * FastAdmin自定义日期选择器
 * 支持工作日、周末、自定义工作日、指定日期、禁用日期等限制
 * 支持从控制器传递配置数据
 */
define(['jquery', 'moment'], function($, moment) {
    'use strict';

    // 注入CSS样式
    if (!$('#custom-datetimepicker-styles').length) {
        var styles = `
            <style id="custom-datetimepicker-styles">
                .bootstrap-datetimepicker-widget .datepicker table td.day:not(.disabled):not(.old):not(.new) {
                    background-color: #d4edda !important;
                    color: #155724 !important;
                    border: 1px solid #c3e6cb !important;
                    font-weight: bold !important;
                }
                .bootstrap-datetimepicker-widget .datepicker table td.day:not(.disabled):not(.old):not(.new):hover {
                    background-color: #28a745 !important;
                    color: white !important;
                }
                .bootstrap-datetimepicker-widget .datepicker table td.today:not(.disabled) {
                    background-color: #fff3cd !important;
                    color: #856404 !important;
                    border: 1px solid #ffeaa7 !important;
                }
                .bootstrap-datetimepicker-widget .datepicker table td.disabled {
                    background-color: #f8f9fa !important;
                    color: #6c757d !important;
                }
            </style>
        `;
        $('head').append(styles);
    }

    // 全局配置对象，用于存储从控制器传递的配置
    window.DateRestrictionConfig = window.DateRestrictionConfig || {};

    $.fn.restrictedDatetimepicker = function(options) {
        var defaults = {
            format: 'YYYY-MM-DD',
            locale: 'zh-cn',
            sideBySide: true,
            showTodayButton: true,
            showClear: true,
            showClose: true
        };

        // 如果第一个参数是字符串，则作为方法调用
        if (typeof options === 'string') {
            var method = options;
            var args = Array.prototype.slice.call(arguments, 1);
            var result;
            
            this.each(function() {
                var $this = $(this);
                var data = $this.data('restrictedDatetimepicker');
                
                if (!data) {
                    console.error('restrictedDatetimepicker 未初始化');
                    return;
                }
                
                switch (method) {
                    case 'updateConfig':
                        if (args[0]) {
                            data.config = $.extend({}, data.config, args[0]);
                            // 重新生成禁用日期
                            var disabledDates = generateDisabledDates(data.config);
                            $this.data('DateTimePicker').disabledDates(disabledDates);
                            $this.trigger('restriction.updated', {config: data.config});
                        }
                        break;
                        
                    case 'getConfig':
                        result = data.config;
                        break;
                        
                    case 'validateDate':
                        if (args[0]) {
                            var testDate = moment(args[0]);
                            var disabledDates = generateDisabledDates(data.config);
                            result = disabledDates.indexOf(testDate.format('YYYY-MM-DD')) === -1;
                        }
                        break;
                        
                    case 'destroy':
                        $this.data('DateTimePicker').destroy();
                        $this.removeData('restrictedDatetimepicker');
                        break;
                        
                    default:
                        console.error('未知方法:', method);
                }
            });
            
            return result !== undefined ? result : this;
        }

        return this.each(function() {
            var $this = $(this);
            var dtpOptions = $.extend({}, defaults, options);
            
            // 提取自定义选项 - 支持两种方式：直接选项或restrictionConfig对象
            var customOptions = {};
            
            if (dtpOptions.restrictionConfig) {
                // 使用restrictionConfig对象
                customOptions = $.extend({}, dtpOptions.restrictionConfig);
                delete dtpOptions.restrictionConfig;
            } else {
                // 使用直接选项
                customOptions = {
                    restrictionType: dtpOptions.restrictionType,
                    allowedDates: dtpOptions.allowedDates,
                    allowedWeekdays: dtpOptions.allowedWeekdays,
                    disabledDates: dtpOptions.disabledDates,
                    configKey: dtpOptions.configKey
                };
                
                // 从选项中移除自定义属性
                delete dtpOptions.restrictionType;
                delete dtpOptions.allowedDates;
                delete dtpOptions.allowedWeekdays;
                delete dtpOptions.disabledDates;
                delete dtpOptions.configKey;
            }

            // 从全局配置中读取数据
            if (customOptions.configKey && window.DateRestrictionConfig[customOptions.configKey]) {
                var config = window.DateRestrictionConfig[customOptions.configKey];
                customOptions.restrictionType = config.restrictionType || customOptions.restrictionType;
                customOptions.allowedDates = config.allowedDates || customOptions.allowedDates;
                customOptions.allowedWeekdays = config.allowedWeekdays || customOptions.allowedWeekdays;
                customOptions.disabledDates = config.disabledDates || customOptions.disabledDates;
            }

            // 生成禁用日期数组
            if (customOptions.restrictionType) {
                var disabledDates = generateDisabledDates(customOptions);
                if (disabledDates.length > 0) {
                    dtpOptions.disabledDates = disabledDates;
                }
            }

            // 保存配置到元素数据中
            $this.data('restrictedDatetimepicker', {
                config: customOptions
            });

            // 初始化日期选择器
            $this.datetimepicker(dtpOptions);
            
            // 触发初始化完成事件
            $this.trigger('restriction.applied', {config: customOptions});
        });
    };

    // 生成禁用日期的函数
    function generateDisabledDates(customOptions) {
        var disabledDates = [];
        var startDate = moment().subtract(1, 'year');
        var endDate = moment().add(2, 'years');
        var currentDate = startDate.clone();

        while (currentDate.isSameOrBefore(endDate)) {
            var shouldDisable = false;
            var dateString = currentDate.format('YYYY-MM-DD');

            switch (customOptions.restrictionType) {
                case 'workdays':
                    // 禁用周末（周六=6，周日=0）
                    shouldDisable = currentDate.day() === 0 || currentDate.day() === 6;
                    break;

                case 'weekends':
                    // 禁用工作日（周一到周五）
                    shouldDisable = currentDate.day() >= 1 && currentDate.day() <= 5;
                    break;

                case 'custom':
                    // 自定义工作日，禁用不在允许列表中的日期
                    if (customOptions.allowedWeekdays && customOptions.allowedWeekdays.length > 0) {
                        shouldDisable = customOptions.allowedWeekdays.indexOf(currentDate.day()) === -1;
                    }
                    break;

                case 'specific':
                    // 指定日期，禁用不在允许列表中的日期
                    if (customOptions.allowedDates && customOptions.allowedDates.length > 0) {
                        shouldDisable = customOptions.allowedDates.indexOf(dateString) === -1;
                    }
                    break;

                case 'disabled':
                    // 禁用特定日期
                    if (customOptions.disabledDates && customOptions.disabledDates.length > 0) {
                        shouldDisable = customOptions.disabledDates.indexOf(dateString) !== -1;
                    }
                    break;
            }

            if (shouldDisable) {
                disabledDates.push(currentDate.format('YYYY-MM-DD'));
            }

            currentDate.add(1, 'day');
        }

        return disabledDates;
    }

    // 预设配置方法
    $.fn.workdaysOnly = function(options) {
        return this.restrictedDatetimepicker($.extend({}, options, {
            restrictionType: 'workdays'
        }));
    };

    $.fn.weekendsOnly = function(options) {
        return this.restrictedDatetimepicker($.extend({}, options, {
            restrictionType: 'weekends'
        }));
    };

    $.fn.customWeekdays = function(allowedWeekdays, options) {
        return this.restrictedDatetimepicker($.extend({}, options, {
            restrictionType: 'custom',
            allowedWeekdays: allowedWeekdays
        }));
    };

    $.fn.specificDates = function(allowedDates, options) {
        return this.restrictedDatetimepicker($.extend({}, options, {
            restrictionType: 'specific',
            allowedDates: allowedDates
        }));
    };

    $.fn.disableDates = function(disabledDates, options) {
        return this.restrictedDatetimepicker($.extend({}, options, {
            restrictionType: 'disabled',
            disabledDates: disabledDates
        }));
    };

    // 从控制器配置初始化
    $.fn.fromControllerConfig = function(configKey, options) {
        return this.restrictedDatetimepicker($.extend({}, options, {
            configKey: configKey
        }));
    };

    // 工具方法：设置全局配置
    window.setDateRestrictionConfig = function(key, config) {
        window.DateRestrictionConfig[key] = config;
    };

    // 工具方法：获取全局配置
    window.getDateRestrictionConfig = function(key) {
        return window.DateRestrictionConfig[key] || null;
    };

    // 返回jQuery插件
    return $;
});